import { useState, useEffect } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import { ICompany, IKey, IRecruit, IUser } from "../../types";
import { useHistory } from "react-router-dom";
import * as api from "../../services/company.services";
import * as userApi from "../../services/user.services";
import style from "./style.module.css";
import "swiper/swiper-bundle.min.css";

import HomeSearchItem from "../../components/HomeSearchItem";
import HomeCompanyItem from "../../components/HomeCompanyItem";
import HomeRecruitItem from "../../components/HomeRecruitItem";
import { Link } from "react-router-dom";

export default function Home() {
  const [companyData, setCompanyData] = useState<ICompany[]>([]);
  const [userData, setUserData] = useState<IUser>();
  const [keyData, setkeyData] = useState<IKey[]>([]);
  const [recruiData, setRecruiData] = useState<IRecruit[]>([]);
  const [area, setArea] = useState("武汉");
  const [size, setSize] = useState<number>(5); //相似职位当前显示条目数量
  const [searchText, setSearchText] = useState<string>("");
  const history = useHistory();

  useEffect(() => {
    const getData = async () => {
      const max = 8;
      const min = 0;
      let companyRows = await api.hotCompany();
      let keyRows = await api.hotKeys();
      let recruitRows = await api.hotrecruit({ city: area });
      if (companyRows.stat === "OK") {
        setCompanyData(companyRows.result.slice(min, max));
      }
      if (keyRows.stat === "OK") {
        setkeyData(keyRows.result);
      }
      if (recruitRows.stat === "OK") {
        setRecruiData(recruitRows.result);
      }
    };
    getData();
  }, [area]);

  useEffect(() => {
    const userinfo = async () => {
      let result = await userApi.userInfo();
      if (result.stat === "OK") {
        setUserData(result.data);
      } else {
        history.push("/");
      }
    };
    userinfo();
  }, [history]);

  const login = () => {
    if (userData !== undefined) {
      return (
        <Link to="/Mine" className={style.loginUser}>
          <img src={`/api/user/download/${userData._id}`} alt="" />
        </Link>
      );
    } else {
      return (
        <Link to="/login" className={style.login}>
          登录/注册
        </Link>
      );
    }
  };

  const goSearch = (keyWord: string) => {
    history.push({ pathname: `/search`, state: { area, keyWord } });
  };

  const getArea = (city: string) => {
    setArea(city);
  };

  return (
    <div className={style.home}>
      <div className={style.banner}>
        <div className={style.title}></div>
        <div className={style.building}></div>
        <div className={style.logo}></div>
        {login()}
        <div className={style.search}>
          <form method="get" className={style.searchForm}>
            <div className={style.searchWrap}>
              <button
                className={style.searchBtn}
                onClick={() => goSearch(searchText)}
              >
                搜索
              </button>
              <input
                type="search"
                className={style.searchText}
                onChange={(event) => setSearchText(event.target.value)}
                autoComplete="off"
                placeholder="搜索职位/公司"
              />
              <HomeSearchItem city={area} getArea={getArea} />
            </div>
          </form>
        </div>
      </div>
      <main className={style.main}>
        <div className={style.keys}>
          <h4 className={style.mainTitle}>热门职位</h4>
          <ul className={style.keysList}>
            {keyData.map((item, index) => {
              return (
                <li
                  className={style.keysItem}
                  key={item._id}
                  onClick={() => goSearch(item.name)}
                >
                  {item.name}
                </li>
              );
            })}
          </ul>
        </div>
        <div className={style.company}>
          <h4 className={style.mainTitle}>热门企业</h4>
          <Swiper
            style={{ zIndex: 0 }}
            className={style.swiperWrap}
            slidesPerColumnFill={"row"}
            height={200}
            slidesOffsetAfter={20}
            spaceBetween={12}
            slidesPerView={2}
            slidesPerColumn={2}
          >
            {companyData?.slice(0, 8).map((item, index) => {
              return (
                <SwiperSlide key={index} className={style.swiper}>
                  <HomeCompanyItem company={item} key={item._id} />
                </SwiperSlide>
              );
            })}
          </Swiper>
        </div>
        <div className={style.recruit}>
          <h4 className={`${style.mainTitle} ${style.companyTitle}`}>
            职位推荐
          </h4>
          <ul className={style.recruitList}>
            {recruiData?.map((item, index) => {
              if (index < size) {
                return <HomeRecruitItem recruit={item} key={item._id} />;
              } else {
                return null;
              }
            })}
            <div className={style.complete} onClick={() => setSize(size + 5)}>
              {size >= recruiData.length ? "没有更多了" : "加载更多"}
            </div>
          </ul>
        </div>
      </main>
    </div>
  );
}
